package cn.me.alphamq.nameserver.config.cluster;

import cn.me.alphamq.nameserver.enumeration.ReplicationModeEnum;
import cn.me.alphamq.common.util.PropertiesUtil;

import java.util.Properties;

/**
 * 集群的配置类
 *
 * @author f
 */
public class ClusterProperties {

    /**
     * 集群的复制模式
     */
    private final ReplicationModeEnum replicationModeEnum;

    /**
     * 主从复制模式的配置
     */
    private MasterSlaveReplicationProperties masterReplicationProperties;

    /**
     * 链式复制模式的配置
     */
    private ChainReplicationProperties chainReplicationProperties;

    public ClusterProperties(ReplicationModeEnum replicationModeEnum) {
        this.replicationModeEnum = replicationModeEnum;
    }

    /**
     * 根据 properties 加载一个集群配置的对象
     *
     * @param properties 配置对象
     * @return 填充配置的对象
     */
    public static ClusterProperties load(Properties properties) {
        ReplicationModeEnum mode = ReplicationModeEnum.of(
                PropertiesUtil.getNotNullProperty(properties, "nameserver.replication.mode")
        );

        ClusterProperties clusterProperties = new ClusterProperties(mode);
        if (ReplicationModeEnum.STANDALONE == mode) {
            // 对于单机模式，无需配置
            return clusterProperties;
        } else if (ReplicationModeEnum.MASTER_SLAVE == mode) {
            // 对于主从复制集群模式，配置主从复制信息
            clusterProperties.masterReplicationProperties = MasterSlaveReplicationProperties.load(properties);
        } else if (ReplicationModeEnum.CHAIN == mode) {
            // 对于链式复制集群模式，配置链式复制信息
            clusterProperties.chainReplicationProperties = ChainReplicationProperties.load(properties);
        }
        return clusterProperties;
    }

    public ReplicationModeEnum getReplicationModeEnum() {
        return replicationModeEnum;
    }

    public MasterSlaveReplicationProperties getMasterReplicationProperties() {
        return masterReplicationProperties;
    }

    public ChainReplicationProperties getChainReplicationProperties() {
        return chainReplicationProperties;
    }
}
